package com.cyzy.chatai.controller;

import com.cyzy.chatai.socket.ChatWebSocket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/websocket")
@CrossOrigin(origins = "*")
public class WebSocketController {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketController.class);

    private final ChatWebSocket chatWebSocket;

    // 构造器注入
    public WebSocketController(ChatWebSocket chatWebSocket) {
        this.chatWebSocket = chatWebSocket;
    }

    /**
     * 获取当前WebSocket连接信息
     */
    @GetMapping("/info")
    public ResponseEntity<Map<String, Object>> getWebSocketInfo() {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("activeConnections", chatWebSocket.getConnectionCount());
        response.put("sessionIds", chatWebSocket.getSessions().keySet());
        logger.info("获取WebSocket连接信息 - 当前连接数: {}", chatWebSocket.getConnectionCount());
        return ResponseEntity.ok(response);
    }

    /**
     * 向所有连接广播消息
     */
    @PostMapping("/broadcast")
    public ResponseEntity<Map<String, Object>> broadcastMessage(@RequestBody Map<String, String> request) {
        String message = request.get("message");
        if (message == null || message.trim().isEmpty()) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "广播消息内容不能为空");
            return ResponseEntity.badRequest().body(errorResponse);
        }

        int sentCount = 0;
        for (WebSocketSession session : chatWebSocket.getSessions().values()) {
            try {
                if (session.isOpen()) {
                    session.sendMessage(new TextMessage("📢 系统广播: " + message));
                    sentCount++;
                }
            } catch (IOException e) {
                logger.error("广播消息到会话 {} 失败: {}", session.getId(), e.getMessage());
            }
        }
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "消息已广播到 " + sentCount + " 个客户端");
        response.put("sentCount", sentCount);
        logger.info("广播消息成功 - 消息: '{}'，发送到 {} 个客户端", message, sentCount);
        return ResponseEntity.ok(response);
    }
}



